﻿#region

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Minion.Win.Client.Constants;
using Minion.Win.Client.Helper;
using Minion.Win.Client.IoC;
using Minion.Win.Client.Models;
using Minion.Win.Client.Service;
using Minion.Win.Client.ViewModels;
using Windows.Devices.Geolocation;

#endregion

namespace Minion.Win.Client.Views
{
    public partial class LocationItemList : PhoneApplicationPage
    {
        private readonly ProgressIndicator _progress = new ProgressIndicator
            {
                IsIndeterminate = true,
                IsVisible = false,
                Text = "Loading..."
            };

        public LocationItemList()
        {
            InitializeComponent();
            SystemTray.SetProgressIndicator(this, _progress);
        }

        private void GetLocationItems()
        {
            if (!AppSettings.LocationConsentSetting) return;

            if (!App.Tracking)
            {
                if (App.Geolocator == null)
                {
                    App.Geolocator = new Geolocator();
                }
                App.Geolocator.DesiredAccuracy = PositionAccuracy.High;
                App.Geolocator.DesiredAccuracyInMeters = 1;
                App.Geolocator.MovementThreshold = 5; // The units are meters.
                App.Geolocator.PositionChanged += geolocator_PositionChanged;
                App.Tracking = true;
            }
            else
            {
                App.Geolocator.PositionChanged -= geolocator_PositionChanged;
                App.Geolocator = null;
                App.Tracking = false;
                App.Geolocator = new Geolocator {DesiredAccuracy = PositionAccuracy.High, MovementThreshold = 5, DesiredAccuracyInMeters = 1};
                App.Geolocator.PositionChanged += geolocator_PositionChanged;
                App.Tracking = true;
            }
        }

        public void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    _progress.IsVisible = true;
                });
            var lat = Math.Round(args.Position.Coordinate.Latitude, 6);
            var lon = Math.Round(args.Position.Coordinate.Longitude, 6);
            var locationItems = Container.Get<IDataService>(App.Mode).GetLocationItems(lat, lon);
            App.CurrentLocationDetails = locationItems;
            Dispatcher.BeginInvoke(() =>
                {
                    DataContext = Converter.ConvertToLocationItemListViewModel(locationItems).ToList();
                    _progress.IsVisible = false;
                });
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            GetLocationConsent();
            if (!AppSettings.LocationConsentSetting)
            {
                MessageBox.Show("You have disabled location access by this app. Please set it in the settings page.",
                                "Location", MessageBoxButton.OK);
            }

            GetLocationItems();
        }

        public void GetLocationConsent()
        {
            if (AppSettings.LocationConsentSetting) return;

            var result = MessageBox.Show("This app accesses your phone's location. Is that ok?",
                                         "Location",
                                         MessageBoxButton.OKCancel);

            AppSettings.LocationConsentSetting = result == MessageBoxResult.OK;

            AppSettings.Save();
        }

        private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selItem = LocationItemSelector.SelectedItem as LocationItemListViewModel;
            if (selItem == null)
                return;

            //find the locationitemdetailID
            var locationItem = Utilities.FindObject<LocationItem>(App.CurrentLocationDetails, selItem.Id);
            string locationItemDetailId = string.Empty;
            if (locationItem != null)
                locationItemDetailId = locationItem.LocationItemDetails.FirstOrDefault().Id.ToString();
            switch (selItem.ItemType)
            {
                case ItemType.Information:
                    NavigationService.Navigate(new Uri("/Views/LocationItemDetail.xaml?id=" + locationItemDetailId,
                                                       UriKind.RelativeOrAbsolute));
                    break;
                case ItemType.Notification:
                    NavigationService.Navigate(new Uri("/Views/NotificationComposer.xaml?id=" + locationItemDetailId,
                                                       UriKind.RelativeOrAbsolute));
                    break;
            }
        }

        private void AddItem_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/AddLocationItem.xaml",
                                                       UriKind.RelativeOrAbsolute));
        }
    }
}